from __future__ import print_function
from textwrap import dedent
import logging
from deploy.util import system
from deploy.util.arg_validators import exclude_group_options
from deploy import decorators, terminal
from deploy.devices.lvm.common import create_parser, rollback_osd
from deploy.devices.lvm.prepare import Prepare
from deploy.devices.lvm.activate import Activate

logger = logging.getLogger(__name__)


class Create(object):

    help = 'Create a new OSD from  an LVM device'

    def __init__(self, argv):
        self.argv = argv

    def create(self, args):
        if not args.osd_fsid:
            args.osd_fsid = system.generate_uuid()
        prepare_step = Prepare([])
        prepare_step.safe_prepare(args)
        osd_id = prepare_step.osd_id
        try:
            # we try this for activate only when 'creating' an OSD, because a rollback should not
            # happen when doing normal activation. For example when starting an OSD, systemd will call
            # activate, which would never need to be rolled back.
            Activate([]).activate(args)
        except Exception:
            logger.exception('lvm activate was unable to complete, while creating the OSD')
            logger.info('will rollback OSD ID creation')
            rollback_osd(args, osd_id)
            raise
        terminal.success("superx-deploy lvm create successful for: %s" % args.data)

    def main(self):
        sub_command_help = dedent("""
        Create an OSD by assigning an FSID, formatting and mounting the volume, adding
        all the metadata to the logical volumes using LVM tags, and starting
        the superx daemon.

        Existing logical volume (lv) or device:

            superx-deploy lvm create --data {vg name/lv name} --journal /path/to/device

        Or:

            superx-deploy lvm create --data {vg name/lv name} --journal {vg name/lv name}

        """)
        parser = create_parser(
            prog='superx-deploy lvm create',
            description=sub_command_help,
        )
        if len(self.argv) == 0:
            print(sub_command_help)
            return
        exclude_group_options(parser, groups=['bluestore'], argv=self.argv)
        args = parser.parse_args(self.argv)
        # Default to bluestore here since defaulting it in add_argument may
        # cause both to be True
        if not args.bluestore:
            args.bluestore = True
        self.create(args)
